#!/usr/bin/env python
# -*- coding: utf-8 -*-

from twisted.internet import protocol, reactor
import SocketTools
import RobotHandle
import socket

class RobotConnection(protocol.Protocol):
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(5)
        self.sock.connect(('127.0.0.1', 9876))

        self.tools = SocketTools.StructProtocol()
        self.count = 0
        print
        print '单元测试开始:'

    def dataReceived(self, data):
        self.sock.sendall(data)

        self.tools.putData(data)

        while 1:
            message = self.tools.getOnce()
            if message:
                self.count += 1
                ret = RobotHandle.Handle(message, self)
                print '\t', self.count, ret[1]

                try:
                    self.transport.write(self.tools.pack(ret[0][0], ret[0][1]))
                except:
                    pass
            else:
                break
        # self.transport.write(data)

class RobotFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return RobotConnection()

reactor.listenTCP(8000, RobotFactory())
reactor.run()